<script setup lang="ts">
import RoomStatus from './components/RoomStatus.vue'
import io, { Socket } from 'socket.io-client'
import { nextTick, onMounted, onUnmounted, ref } from 'vue'
import { baseURL } from '@/utils/request'
import { useUserStore } from '@/stores'
import { useRoute } from 'vue-router'
import { MsgType } from '@/enums'
import type { Message, TimeMessages } from '@/types/room'
import RoomAction from './components/RoomAction.vue';
import RoomMessage from './components/RoomMessage.vue';
import type { ConsultOrderItem } from '@/types/consult'
import { getConsultOrderDetail } from '@/apis/consult'
import { OrderType } from '@/enums';
const consult = ref<ConsultOrderItem>()

const list = ref<Message[]>([])
const store = useUserStore()
const route = useRoute()
const connected = ref(false)
let socket: Socket
onUnmounted(() => {
    socket.close()
})
onMounted(async () => {
    const res = await getConsultOrderDetail(route.query.orderId as string)
    consult.value = res.data
    // 建立链接，创建 socket.io 实例
    socket = io(baseURL, {
        auth: {
            token: `Bearer ${store.user?.token}`
        },
        query: {
            orderId: route.query.orderId
        }
    })

    socket.on('connect', async () => {
        // 建立连接成功
        list.value = []
        console.log('connect')
        connected.value = true
    })
    // 订单状态 在onMounted注册
    socket.on('statusChange', async () => {
        const res = await getConsultOrderDetail(route.query.orderId as string)
        consult.value = res.data
    })


    socket.on('error', (event) => {
        // 错误异常消息
        console.log('error', event)
    })

    // chat message 接收消息事件，由后台约定，可变
    socket.on('chat message', (ev) => {
        // ev 是服务器发送的消息
        console.log(ev);
    })

    socket.on('disconnect', () => {
        // 已经断开连接
        console.log('disconnect')
    })
    // 聊天记录
    socket.on('chatMsgList', ({ data }: { data: TimeMessages[] }) => {
        // 准备转换常规消息列表
        const arr: Message[] = []
        data.forEach((item, i) => {
            if (i === 0) time.value = item.createTime
            arr.push({
                msgType: MsgType.Notify,
                msg: { content: item.createTime },
                createTime: item.createTime,
                id: item.createTime
            })
            arr.push(...item.items)
        })

        // 追加到聊天消息列表
        list.value.unshift(...arr)
        loading.value = false
        if (!data.length) {
            return showFailToast('没有聊天记录了')
        }
        nextTick(() => {
            if (initialMsg.value) {
                window.scrollTo(0, document.body.scrollHeight)
                socket.emit('updateMsgStatus', arr[arr.length - 1].id)
                initialMsg.value = false
            }
        })

    })
    // 接收消息 在onMounted注册
    socket.on('receiveChatMsg', async (event) => {
        list.value.push(event)
        await nextTick()
        socket.emit('updateMsgStatus', event.id)
        window.scrollTo(0, document.body.scrollHeight)
    })

})
const initialMsg = ref(true)
const time = ref(dayjs().format('YYYY-MM-DD HH:mm:ss'))

const sendText = (text: string) => {
    // 发送信息需要  发送人  收消息人  消息类型  消息内容
    socket.emit('sendChatMsg', {
        from: store.user?.id,
        to: consult.value?.docInfo?.id,
        msgType: MsgType.MsgText,
        msg: { content: text }
    })
}


import type { Image } from '@/types/consult'
import dayjs from 'dayjs'
import { showFailToast, Toast } from 'vant'

const sendImage = (img: Image) => {
    socket.emit('sendChatMsg', {
        from: store.user?.id,
        to: consult.value?.docInfo?.id,
        msgType: MsgType.MsgImage,
        msg: { picture: img }
    })
}

const loading = ref(false)
const onRefresh = () => {
    socket.emit('getChatMsgList', 20, time.value, route.query.orderId)
}

import { provide } from 'vue'
provide('consult', consult)

const completeEva = (score: number) => {
    const item = list.value.find((item) => item.msgType === MsgType.CardEvaForm)
    if (item) {
        item.msg.evaluateDoc = { score }
        item.msgType = MsgType.CardEva
    }
}
provide('completeEva', completeEva)


</script>

<template>
    <div class="room-page">
        <cp-nav-bar title="问诊室" />
        <room-status :status="consult?.status" :countdown="consult?.countdown" />
        <room-action :disabled="consult?.status !== OrderType.ConsultChat" @send-text="sendText"
            @send-image="sendImage" />

        <van-pull-refresh v-model="loading" @refresh="onRefresh">
            <room-message :list="list" v-if="connected" />
        </van-pull-refresh>

    </div>
</template>
<style lang="scss" scoped>
.room-page {
    padding-top: 90px;
    padding-bottom: 60px;
    min-height: 100vh;
    box-sizing: border-box;
    background-color: var(--cp-bg);

    .van-pull-refresh {
        width: 100%;
        min-height: calc(100vh - 150px);
    }
}
</style>
